import dictionary from './dictionary'
import {
  clearUserInfo,
  clearToken
} from 'assets/js/cache'
import DEFAULT_IMG_MINI from 'assets/image/placeholder_mini.png'
import { logout } from 'api/account'

export const isAndriod = function() {
  const u = navigator.userAgent
  return u.indexOf('Android') > -1 || u.indexOf('Linux') > -1
}
export const isIOS = function() {
  const u = navigator.userAgent
  return !!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/)
}

export function getThumbPic(thumbPic, defSrc, m, w, h, clearCache) {
  if (thumbPic) {
    return `${thumbPic}?imageView2/${(m >= 0 ? m : 0)}/w/${(w > 0 ? w : 120)}/h/${(h > 0 ? h : 100)}${(clearCache ? '&=t' + Math.random() : '')}`
  }
  return defSrc || DEFAULT_IMG_MINI
}

export const formatPhone = function(phone, type = 'text') {
  /// <summary>格式化手机号码</summary>
  if (!phone) return ''
  var str = phone.replace(/\s/g, '')
  if (type === 'input') {
    var len = str.length
    if (len <= 3) {
      return str
    } else if (len > 3 && len < 7) {
      return str.substring(0, 3) + ' ' + str.substring(3, len)
    } else if (len <= 13) {
      return (
        str.substring(0, 3) +
        ' ' +
        str.substring(3, 7) +
        ' ' +
        str.substring(7, len)
      )
    }
  } else {
    var PHONE_NUMBER = 11
    if (phone.length === PHONE_NUMBER) {
      return str.replace(/(.{3})(.{4})(.{4})/g, '$1 $2 $3')
    }
  }
}

export const gapNumber = function(str, gapSize) {
  if (!str) return str
  // let size = gapSize || 4
  let val = str.replace(/s/g, '')
  if (val === '') return ''
  return val.replace(/(.{4})/g, '$1 ')
}

export function getImgKey(path, key) {
  return path ? path.substr(path.indexOf(key)) : ''
}

export function getRequest(url) {
  const newUrl = url || window.location.search // 获取url中"?"符后的字串
  var theRequest = {}
  if (newUrl.indexOf('?') !== -1) {
    const str = newUrl.substr(1)
    const strs = str.split('&')
    for (var i = 0; i < strs.length; i++) {
      theRequest[strs[i].split('=')[0]] = decodeURIComponent(
        strs[i].split('=')[1]
      )
    }
  }
  return theRequest
}

export function getMessageBoxHtml(
  title = '发送成功',
  text = '',
  iconType = ''
) {
  return `<div class="mint-mesbox-body">${
    iconType ? `<i class="fdx-icon-${iconType}"></i>` : ''
  }${title}</div><p class="mint-msgbox-message-text">${text}</p>`
}

export async function logoutFun() {
  try {
    await logout()
    clearUserInfo()
    clearToken()
    location.href = location.href.replace(/#.+/gi, '')
  } catch (ex) {}
}